let db = wx.cloud.database()
let love = db.collection('express_love')
let comment_db = db.collection('comment')
let answer_db = db.collection('answer')
const app = getApp().globalData

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    show1: false,
    value: "",
    value2: "",
    value3: "",
    images: [],
    images_success: [],
    images_success_size: 0,
    lovelist: [],
    imageslist: [],
    comment_to: "",
    commentlist: [],
    love_id: "",
    activeName: '1',
  },
  show1(event) {
    console.log(event.currentTarget.dataset.loveid)
    this.setData({
      show1: true,
      comment_to: event.currentTarget.dataset.id,
      love_id: event.currentTarget.dataset.loveid
    })

    this.findComment(event.currentTarget.dataset.loveid)
  },
  onChange(event) {
    this.setData({
      activeName: event.detail,
    });
  },
  answer(){
    wx.createSelectorQuery().select('.input')
    console.log( wx.createSelectorQuery().select('.input'));
  },
  show() {
    this.setData({
      show: true,
    })

  },
  // 上传图片（云储存）

  upload() {
    let that = this;
    wx.chooseMedia({ //异步方法
      count: 6, //最多选择图片数量
      mediaType: ['image'],
      camera: 'back',
      sizeType: ['original', 'compressed'], //选择的图片尺寸 原图，压缩图
      sourceType: ['album', 'camera'], //相册选图，相机拍照

      success(res) {
        console.log("222", res.tempFiles);
        //const tempFilePaths = res.tempFilePaths
        that.setData({
          images: res.tempFiles
        });
        console.log(that);
        console.log(res.tempFiles);
        console.log("选择成功", res)
      }
    })
  },

  uploadImage() {
    return new Promise((resolve, reject) => {
      let that = this
      let res2 = []
      for (let index = 0; index < this.data.images.length; index++) {
        wx.cloud.uploadFile({ //上传至微信云存储
          cloudPath: 'myImage/' + new Date().getTime() + "_" + Math.floor(Math.random() * 1000) + ".jpg", //使用时间戳加随机数给图片命名
          filePath: that.data.images[index].tempFilePath, // 本地文件路径
          success: res => {
            // 返回文件 ID

            wx.cloud.downloadFile({
              fileID: res.fileID, // 文件 ID
              success: res => {
                // 返回临时文件路径
                console.log(res.tempFilePath);   
                that.data.images_success[index] = res.tempFilePath
                res2.push(res.tempFilePath)
                this.setData({
                  images: res2
                })
                console.log(res)
                return Promise.resolve()
              },
              fail: console.error
            })
            console.log(res);
            that.data.images_success_size = that.data.images_success_size + 1;

            if (that.data.images_success_size == that.data.images.length) {} else {
              that.uploadImage(index + 1)
            }
          },
          fail: err => {
            that.setData({
              images_success: [],
              images_success_size: 0
            })
            wx.showToast({
              icon: 'none',
              title: '上传失败，请重新上传',
            })
          }
        })

      }
    })



  },

  //提交表单添加到数据库
  addBtn: async function (e) {
    let that = this;
    console.log(app.userInfo);
    if (that.data.value.length < 1) {
      wx.showToast({
        title: '请输入表白对象',
      })
      return;
    }
    if (that.data.value2.length < 10) {
      wx.showToast({
        title: '内容需大于10',
      })
      return;
    }
    if (that.data.images.length > 0) { //1、判断是否有图片
      that.setData({
        //3、给上传图片初始化一个长度，上传成功的数组和已有的数组一致
        images_success: that.data.images
      })
      that.uploadImage().then(RES => {
        console.log(this.data.images);
      }) //2、有图片时先上传第一张

    }
    if (app.openid.length > 0) {

      love.add({
          data: {
            createTime: new Date().toLocaleString('zh-cn', {
              hour12: false
            }),
            images: that.data.images,
            name: app.userInfo.nickName,
            to: that.data.value,
            info: that.data.value2,
            is_select: false,
          }
        })
        .then(
          res => {
            if (res.errMsg == "collection.add:ok") {
              console.log(res);
              this.findLove()
              // 提示
              wx.showToast({
                title: '发表成功',
              })
            }
          }
        )
    }

    this.setData({
      value: "",
      value2: "",
      images: [],
      _openid: ""
    })
    console.log(1);
    this.findLove()
  },
  preview(event) {
    this.data.imageslist = []
    let currentUrl = event.currentTarget.dataset.src
    let index = event.currentTarget.dataset.index
    this.data.lovelist[index].images.forEach(item => {
      this.data.imageslist.push(item.tempFilePath)
    })
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: this.data.imageslist // 需要预览的图片http链接列表
    })
  },

  async findLove() {
    db = wx.cloud.database()
    love = db.collection('express_love')
    comment_db = db.collection('comment')
    answer_db = db.collection('answer')

    await love.orderBy("createTime", "desc").get().then(
      res => {
        if (res.errMsg == "collection.get:ok") {
          console.log("res44", res)
          // 解构赋值
          let {
            data
          } = res;
          console.log(this);

          data.map(
            item => {
              item.createTime = item.createTime.replaceAll(/[\u4e00-\u9fa5]+/g, " ")
              return item
            }
          )
          console.log(data);
          this.setData({
            lovelist: data
          })

        }
      })
  },
  async like(event) {
    console.log(event);
    await love.where({
        _id: event.currentTarget.dataset.id,
      }).get()
      .then(async (res) => {
        console.log(this.data.flag);
        if (res.data[0]._openid == app.openid && res.data[0].is_select) {
          love.where({
              _id: event.currentTarget.dataset.id,
            }).update({
              data: {
                love_count: res.data[0].love_count - 1,
                is_select: false
              }
            })
            .then(
              res => {
                console.log(res)
                if (res.errMsg == "collection.update:ok") {

                  this.findLove()
                  this.setData({
                    flag: false,
                  })

                }
              }
            )
        } else {
          let count = 0
          if (res.data[0].love_count) {
            count = res.data[0].love_count + 1
          } else {
            count = 1
          }

          love.where({
              _id: event.currentTarget.dataset.id,
            }).update({
              data: {
                love_count: count,
                is_select: true,
              }
            })
            .then(
              res => {
                console.log(res)
                if (res.errMsg == "collection.update:ok") {

                  this.findLove()
                  this.setData({
                    flag: false,
                  })

                }
              }
            )
            .catch(err => {
              console.log(err);
            })
        }

      })
  },
  async comment(event) {
    let empty = this.data.value3.trim()
    console.log(event);
    if (empty.length < 1) {
      wx.showToast({
        title: '请输入评论内容',
      })
      return;
    }
    await comment_db.add({
        data: {
          love_id: this.data.love_id,
          info: this.data.value3,
          comment_to: this.data.comment_to,
          createTime: new Date().toLocaleString('zh-cn', {
            hour12: false
          })
        }
      })
      .then(
        async (res) => {
          if (res.errMsg == "collection.add:ok") {
            console.log(res);

            // 提示

            wx.showToast({
              title: '评论成功',
            })
            await love.where({
                _id: this.data.love_id,
              }).get()
              .then(async (res) => {
                console.log(res);
                let length = 0
                if (res.data[0].comment_length) {
                  length = res.data[0].comment_length + 1
                } else {
                  length = 1
                }

                await love.where({
                    _id: this.data.love_id,
                  }).update({
                    data: {
                      comment_length: length
                    }
                  })
                  .then(
                    res => {
                      console.log(res)
                      if (res.errMsg == "collection.update:ok") {

                        this.findLove()


                      }
                    }
                  )
                  .catch(err => {
                    console.log(err);
                  })
              })

            this.findComment(this.data.love_id)
            this.setData({
              value3: "",
            })

          }
        }
      )
  },
  async findComment(id) {
    await comment_db.where({
        love_id: id,
      })
      .get().then(
        res => {
          if (res.errMsg == "collection.get:ok") {
            console.log(res)
            // 解构赋值
            let {
              data
            } = res;
            console.log(this);

            data.map(
              item => {
                item.createTime = item.createTime.replaceAll(/[\u4e00-\u9fa5]+/g, " ")
                return item
              }
            )
            console.log(data);
            this.setData({
              commentlist: data
            })

          }
        })
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  onClose1() {
    this.setData({
      show1: false,
      comment_to: "",
    });
  },
  delPhoto(event) {
    let i = event.currentTarget.dataset.index
    console.log(this.data.images, i);
    this.data.images.splice(i, 1)
    let arr =
      this.setData({
        images: this.data.images
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.findLove()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})